var base_url = getApp().globalData.base_url
var app = getApp();

Page({
  data: {
    selectYearTime: '2021',
    isLoaded: false,
    bill: null
  },
  
  bindYearChange: function (e) {
    this.setData({
      selectYearTime: e.detail.value
    })
    this.refresh()
  },

  onLoad: function () {
    this.refresh()
  },

  startLoad() {
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading();
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({
      title: '加载中...',
    })
  },

  endLoad() {
    //隐藏loading 提示框
    wx.hideLoading();
    //隐藏导航条加载动画
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },

  refresh() {
    let that = this
    let userId = app.globalData.userId
    let fromDate = new Date(this.data.selectYearTime)
    if (this.data.selectYearTime == '2021') {
      var endDate = new Date()
      endDate.setMonth(new Date().getMonth() + 1)
      endDate.setDate(0)
    } else {
      var endDate = new Date(fromDate)
      endDate.setFullYear(Number(this.data.selectYearTime) + 1)
      endDate.setDate(0)
    }
    var url = base_url + '/users/accounts/bills/' + userId + '?fromTime=' + fromDate.valueOf() + '&endTime=' + endDate.valueOf()
    this.startLoad()
    wx.request({
      url: url,
      method: 'GET',
      success(res) {
        if (res.data.resultCode == 200) {
          res.data.data.list.reverse()
          res.data.data.totalAmount = Number(res.data.data.totalAmount).toFixed(2)
          res.data.data.totalIncome = Number(res.data.data.totalIncome).toFixed(2)
          res.data.data.totalExpend = Number(res.data.data.totalExpend).toFixed(2)
          app.globalData.bill = res.data.data
          that.setData({
            isLoaded: true,
            bill: app.globalData.bill
          })
        } else {
          wx.showToast({
            title: '获取账单信息失败',
            icon: 'error',
            duration: 2000
          })
        }
      },
      complete() {
        that.endLoad()
      }
    })
  },

  onShow() {
    if (this.isLoaded) {
      this.setData({
        bill: app.globalData.bill
      })
    }
  },

  onPullDownRefresh: function () {
    this.refresh()
  }
})
